package com.woyao;

import android.Manifest;
import android.app.Application;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.woyao.core.FileUtil;
import com.woyao.core.model.BaseResponse;
import com.woyao.core.model.Demand;
import com.woyao.core.model.GetDemandResponse;
import com.woyao.core.model.GetMyMemberResponse;
import com.woyao.core.model.GetTransactionListResponse;
import com.woyao.core.model.KeyValueList;
import com.woyao.core.model.MemberSummary;
import com.woyao.core.model.TransactionOption;
import com.woyao.core.service.AccountService;
import com.woyao.core.util.Common;
import com.woyao.core.util.ServiceFactory;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import retrofit2.Call;

import static android.view.View.GONE;
import static com.woyao.WoyaoooApplication.userId;

public class DemandNewActivity extends AppCompatActivity  {

    public boolean is_new = false;

    private RecyclerView recyclerView;
    private  MediaAdapter mediaAdapter;
    private ProgressBar progress;

    Button demandClose;
    Button demandView;
    
    private TextView memberTitle;
    private Button addMediaBtn;
    private TextView titleTxt;
    private TextView resourceTxt;

    private  TextView transactionExplan;
    private TextView transactionDetail;


    private TextView referFeeDetail;

    private TextView howTxt;
    private TextView typeTxt;
    private TextView typesText;
    private TextView referFeeTxt;
    private TextView transactionTxt;


    private LinearLayout actionArea;


    List<MemberSummary> members = new ArrayList<MemberSummary>();
    List<TransactionOption> transactionlist = new ArrayList<TransactionOption>();


    boolean changed = false;
    ProgressDialog progressDialog;
    private Demand demand = new Demand();

    private  boolean loading = false;

    Button nextBtn;


    Integer MEMBER_CODE  = 44 ;
    Integer TYPE_CODE  = 77 ;
    Integer HOW_CODE = 88;   //
    Integer TYPES_CODE = 90;   //
    
    Integer TITLE_CODE =  66;
    Integer RESOURCE_CODE =  22;
    Integer REFER_FEE_CODE =  33;
    Integer CHOOSE_MEDIA_CODE =  8;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_demand_edit);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        ab.setDisplayShowHomeEnabled(true); // show or hide the default home button
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setDisplayShowCustomEnabled(true); // enable overriding the default toolbar layout

        nextBtn = (Button) findViewById(R.id.demand_finish);

        progress  =  (ProgressBar)  findViewById(R.id.uploading);

        actionArea =  (LinearLayout) findViewById(R.id.demand_actions);

        transactionTxt =(TextView)findViewById(R.id.id_demand_transaction);
        referFeeTxt =(TextView)findViewById(R.id.id_demand_refer_fee);

        LinearLayout referFeeArea = (LinearLayout) findViewById(R.id.id_demand_refer_fee_area);

        LinearLayout transactionArea = (LinearLayout) findViewById(R.id.id_demand_transaction_area);
        recyclerView = (RecyclerView) findViewById(R.id.demand_medias);

        recyclerView.setLayoutManager(new GridLayoutManager(this,4));//布局管理器
        recyclerView.setItemAnimator(new DefaultItemAnimator());//使用默认的动画效果

        mediaAdapter = new MediaAdapter(this, demand.getMedias());
        mediaAdapter.setChangedHandler(new MediaAdapter.Changed() {
            @Override
            public void Changed(Integer count) {
                demand.setMedias(mediaAdapter.getMedias());
            }
        });
        recyclerView.setAdapter(mediaAdapter);

        howTxt =(TextView)findViewById(R.id.id_demand_how);
        howTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ModifyHow();
            }
        });

        typeTxt =(TextView)findViewById(R.id.id_demand_type);
        typeTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ModifyType();
            }
        });

        typesText =(TextView) findViewById(R.id.id_demand_types);

        typesText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                ModifyTypes();

            }
        });

        transactionArea.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                confirmTransaction();
            }
        });


        referFeeArea.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                renderRefer_feeInput();
            }
        });



        memberTitle = (TextView)findViewById(R.id.demand_member);

        memberTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ( members.size() == 0 ){
                    Intent intent = new Intent();
                    intent.putExtra( "id", 0);

                    intent.setClass( DemandNewActivity.this, ConfirmOrgActivity.class);
                    startActivityForResult(intent ,MEMBER_CODE);
                }else{
                    confirmMember();
                }
            }
        });



        addMediaBtn = (Button) findViewById(R.id.demand_add_media);

        addMediaBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                 addMedia();
                    


            }
        });

        titleTxt = (TextView) findViewById(R.id.id_demand_title);
        titleTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                completeTitle();
            }
        });
        
        resourceTxt = (TextView)findViewById(R.id.id_demand_resource);

        resourceTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                renderResourceInput();
            }
        });

       
        transactionDetail = (TextView)findViewById(R.id.transaction_detail);

        transactionDetail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(DemandNewActivity.this, WebviewActivity.class);
                intent.putExtra("title", "用户帮助");
                intent.putExtra("link", "https://www.woyaooo.com/charge.html#intention");
                startActivity(intent);
            }
        });



        transactionExplan = (TextView)findViewById(R.id.transaction_explanation);
        referFeeDetail = (TextView)findViewById(R.id.refer_fee_detail);

        referFeeDetail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(DemandNewActivity.this, WebviewActivity.class);
                intent.putExtra("title", "用户帮助");
                intent.putExtra("link", "https://www.woyaooo.com/charge.html#refer");
                startActivity(intent);
            }
        });

        nextBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finishIt();

            }
        });

        

        demandView = (Button)findViewById(R.id.demand_view_detail);
        demandView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass( DemandNewActivity.this, ChanceViewActivity.class);
                intent.putExtra("id",    demand.getId() );
                startActivity(intent);
            }
        });

        Button setDefaultBtn = (Button)findViewById(R.id.demand_setdefault);
        setDefaultBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Common.setProfileAttrFeedback(DemandNewActivity.this, "demand_id", demand.getId() +"");
            }
        });



        demandClose= (Button)findViewById(R.id.demand_close);
        demandClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String prompt = "";
                if (demand.getAccess_right().equals("public")) {
                    prompt = "关闭吗？";
                }else{
                    prompt = "激活吗？";
                }

                Dialog alertDialog = new AlertDialog.Builder(DemandNewActivity.this).
                        setTitle("信息").
                        setMessage(prompt).
                        setIcon(R.drawable.ic_launcher).
                        setPositiveButton("确定", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                if (demand.getAccess_right().equals("public")) {
                                    setDemandAccessRight("private");
                                }else{
                                    setDemandAccessRight("public");
                                }
                                changed = true;
                            }
                        }).
                        setNegativeButton("取消", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        }).
                        create();
                alertDialog.show();

            }
        });



       
        Intent intent = getIntent();
        is_new = intent.getBooleanExtra("is_new",false);

        if (is_new) {
           
            Integer member_id = intent.getIntExtra( "member_id", 0);
            String member_title = intent.getStringExtra( "member_title");
            if (member_title == null){
                member_title = "" ;
            }

            if (member_id > 0){
                demand.setMember_id( member_id);
                demand.setMember_title(member_title);
                memberTitle.setText(demand.getMember_title());
            }else {
                SharedPreferences shared = getSharedPreferences("login", MODE_PRIVATE);
                demand.setMember_title(shared.getString("title", ""));
                demand.setMember_id(shared.getInt("member_id", 0));
                memberTitle.setText(demand.getMember_title());
            }
            

            this.setTitle("说明我的业务" );

            actionArea.setVisibility(GONE);

        }else {
            demand.setId(  intent.getIntExtra("id",0));
            loadDemand();
        }

        loadUserBasic();
        loadTransactionList();
        loadMembers();

    }

    private void setUserDemand_id( Integer id){
        Application application = getApplication();

        SharedPreferences shared = application.getSharedPreferences("login", MODE_PRIVATE);

        SharedPreferences.Editor editor = shared.edit();
        editor.putInt("demand_id", id);
        WoyaoooApplication.demand_id = id;

        editor.commit();
    }
    private void addMedia(){


        if(ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED){ //权限没有被授予
            /**3.申请授权
             * @param
             *  @param activity The target activity.（Activity|Fragment、）
             * @param permissions The requested permissions.（权限字符串数组）
             * @param requestCode Application specific request code to match with a result（int型申请码）
             *    reported to {@link OnRequestPermissionsResultCallback#onRequestPermissionsResult(
             *    int, String[], int[])}.
             * */



            Dialog alertDialog = new AlertDialog.Builder(this).
                    setTitle("信息").
                    setMessage( "为提供丰富动态信息，上传图片，请授权访问设备的图片资料").
                    setIcon(R.drawable.ic_launcher).
                    setPositiveButton("确定", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            ActivityCompat.requestPermissions(DemandNewActivity.this,
                                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                    520);
                        }
                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                }
            }).
                    create();
            alertDialog.show();
        }else{//权限被授予
            Intent intent = new Intent();
            intent.setType("*/*");
            // start the image capture Intent
            intent.setAction(Intent.ACTION_GET_CONTENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            startActivityForResult(intent, CHOOSE_MEDIA_CODE);
        }

    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        if (requestCode == 520)
        {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
            {
                Intent intent = new Intent();
                intent.setType("*/*");
                // start the image capture Intent
                intent.setAction(Intent.ACTION_GET_CONTENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                startActivityForResult(intent, CHOOSE_MEDIA_CODE);
            } else
            {
                Toast.makeText(DemandNewActivity.this, "权限被拒绝，图片不能正常上传", Toast.LENGTH_SHORT).show();
            }
            return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
    public  void ModifyTypes() {
        Intent intent = new Intent();
        intent.putExtra("from", "search");
        intent.putExtra("title", "请选择寻求的资源");
        KeyValueList kvl = new KeyValueList();
        kvl.setContent( demand.getTypes_list() );
        intent.putExtra("type_list", kvl  );
        intent.setClass(DemandNewActivity.this, FilterType.class);
        startActivityForResult(intent, TYPES_CODE);
    }
   


    private void loadUserBasic(){
        Application application = getApplication();
        SharedPreferences shared = application.getSharedPreferences("login", MODE_PRIVATE);

        try {
            WoyaoooApplication.hasLogin = shared.getBoolean("logged", false);
            WoyaoooApplication.userId = shared.getInt("userId", 0);
            WoyaoooApplication.displayname = shared.getString("displayname", "");;
            WoyaoooApplication.location = shared.getString("location", "");
            WoyaoooApplication.title = shared.getString("title", "");
            WoyaoooApplication.snailview = shared.getString("snailview", "");
            WoyaoooApplication.demand_id = shared.getInt("demand_id", 0);
            WoyaoooApplication.member_id = shared.getInt("member_id", 0);
            WoyaoooApplication.message_num = shared.getInt("message_num", 0);

        }catch (Exception e){

        }

    }
    private void finishIt(){


        if (demand.getTitle().length() < 2 || demand.getTitle().length() > 32 ){

            Dialog alertDialog = new AlertDialog.Builder(DemandNewActivity.this).
                    setTitle("信息").
                    setMessage("请填写标题，最少2个字，最多30字").
                    setIcon(R.drawable.ic_launcher).
                    setPositiveButton("确定", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            completeTitle();
                        }
                    }).
                    create();
            alertDialog.show();

            return;
        }



        if ( demand.getResourcex().length() < 5 ){

            Dialog alertDialog = new AlertDialog.Builder(DemandNewActivity.this).
                    setTitle("信息").
                    setMessage("请具体说明业务，不少于5个字").
                    setIcon(R.drawable.ic_launcher).
                    setPositiveButton("确定", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent();
                            intent.putExtra("type","demandresource");
                            intent.putExtra( "content", demand.getResourcex() );
                            intent.setClass(DemandNewActivity.this,  InputActivity.class);
                            startActivityForResult(intent,RESOURCE_CODE);
                        }
                    }).
                    create();
            alertDialog.show();

            return;
        }

        // if (demand.getMedias().size() == 0){

        //     Dialog alertDialog = new AlertDialog.Builder(DemandNewActivity.this).
        //             setTitle("信息").
        //             setMessage("请上传图片或视频").
        //             setIcon(R.drawable.ic_launcher).
        //             setPositiveButton("确定", new DialogInterface.OnClickListener() {

        //                 @Override
        //                 public void onClick(DialogInterface dialog, int which) {
        //                     addMedia();
        //                 }
        //             }).
        //             create();
        //     alertDialog.show();

        //     return;
        // }

        if (demand.getMedias().size() > 9 ){

            Dialog alertDialog = new AlertDialog.Builder(DemandNewActivity.this).
                    setTitle("信息").
                    setMessage("请上传图片或视频，最多9个").
                    setIcon(R.drawable.ic_launcher).
                    setPositiveButton("确定", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
//                            addMedia();
                        }
                    }).
                    create();
            alertDialog.show();

            return;
        }

        // if (demand.getTransaction() < 0 ){

        //     Dialog alertDialog = new AlertDialog.Builder(DemandNewActivity.this).
        //             setTitle("信息").
        //             setMessage("请选择项目合作要求").
        //             setIcon(R.drawable.ic_launcher).
        //             setPositiveButton("确定", new DialogInterface.OnClickListener() {

        //                 @Override
        //                 public void onClick(DialogInterface dialog, int which) {
        //                 confirmTransaction();
        //                 }
        //             }).
        //             create();
        //     alertDialog.show();

        //     return;
        // }



//        if (demand.getMedias().size() == 0 ){
//
//            Dialog alertDialog = new AlertDialog.Builder(DemandNewActivity.this).
//                    setTitle("信息").
//                    setMessage("请上传图片或视频，至少1个，最多9个").
//                    setIcon(R.drawable.ic_launcher).
//                    setPositiveButton("确定", new DialogInterface.OnClickListener() {
//
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            addMedia();
//                        }
//                    }).
//                    create();
//            alertDialog.show();
//
//            return;
//        }

//        if (demand.getType_list().size() == 0){
//
//            Dialog alertDialog = new AlertDialog.Builder(DemandNewActivity.this).
//                    setTitle("信息").
//                    setMessage(getString(R.string.demand_type)).
//                    setIcon(R.drawable.ic_launcher).
//                    setPositiveButton("确定", new DialogInterface.OnClickListener() {
//
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            ModifyType();
//                        }
//                    }).
//                    create();
//            alertDialog.show();
//
//            return;
//        }
//
//        if (demand.getType_list().size() == 0){
//
//            Dialog alertDialog = new AlertDialog.Builder(DemandNewActivity.this).
//                    setTitle("信息").
//                    setMessage(getString(R.string.demand_types)).
//                    setIcon(R.drawable.ic_launcher).
//                    setPositiveButton("确定", new DialogInterface.OnClickListener() {
//
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            ModifyTypes();
//                        }
//                    }).
//                    create();
//            alertDialog.show();
//
//            return;
//        }

//        Integer countit = 0;
//        for (KeyValue kv : demand.getType_list()){
//            for (KeyValue kv1 : demand.getTypes_list()) {
//                if (kv.getNo().equals(kv1.getNo())) {
//                    countit +=1;
//                    break;
//
//                }
//            }
//        }
//
//        if (countit > 1){
//            Dialog alertDialog = new AlertDialog.Builder(DemandNewActivity.this).
//                    setTitle("信息").
//                    setMessage("拥有和寻求的资源重复了，请检查").
//                    setIcon(R.drawable.ic_launcher).
//                    setPositiveButton("确定", new DialogInterface.OnClickListener() {
//
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//
//                        }
//                    }).
//                    create();
//            alertDialog.show();
//
//            return;
//        }

        if (is_new) {
            addDemand( );
        }else {
            SuceedFinish();
        }
    }

    private void ModifyHow(){
        Intent intent = new Intent();
        intent.putExtra("from", "demand");
        intent.putExtra("title", "请选择合作需求");
        KeyValueList kvl = new KeyValueList();
        kvl.setContent( demand.getHow_list() );
        intent.putExtra("how_list", kvl  );
        intent.setClass(DemandNewActivity.this, FilterHow.class);
        startActivityForResult(intent, HOW_CODE);

    }

    private void ModifyType(){
        Intent intent = new Intent();
        intent.putExtra("from", "demand");
        intent.putExtra("title", "请选择拥有的资源");
        KeyValueList kvl = new KeyValueList();
        kvl.setContent( demand.getType_list() );
        intent.putExtra("type_list", kvl  );
        intent.setClass(DemandNewActivity.this, FilterType.class);
        startActivityForResult(intent, TYPE_CODE);

    }


    int transactionChoice = 0 ;
    private void confirmTransaction( ){

        ArrayList<String> list = new ArrayList<String>();
        int i = 0;
        for ( TransactionOption kv : transactionlist ) {
            list.add(kv.getName());

            if (demand.getTransaction() == kv.getNo() ){
                transactionChoice  = i ;
            }
            i = i+ 1;
        }


        final String[] items =  (String[])list.toArray(new String[0]);

        AlertDialog.Builder singleChoiceDialog =
                new AlertDialog.Builder(DemandNewActivity.this);
        singleChoiceDialog.setTitle("选择项目合作要求");
        // 第二个参数是默认选项，此处设置为0
        singleChoiceDialog.setSingleChoiceItems(items, transactionChoice,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        transactionChoice = which;
                    }
                });
        singleChoiceDialog.setPositiveButton("确 定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (transactionChoice > -1 ){
                            demand.setTransaction(  transactionlist.get(transactionChoice).getNo()  );
                            if (!is_new) {
                                Common.setDemandAttr(demand.getId(), "transaction", demand.getTransaction() + "");
                            }
                            transactionTxt.setText(transactionlist.get(transactionChoice).getName() + "" );
                            transactionTxt.setTextColor(ContextCompat.getColor(DemandNewActivity.this,R.color.colorPrimaryDark));
                        }

                    }
                })
        .setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        }).show();

    }



    int yourChoice = 0 ;
    private void confirmMember( ){


        yourChoice = 0 ;
        ArrayList<String> list = new ArrayList<String>();
        for (int i = 0; i < members.size(); i++) {
            MemberSummary ds = members.get(i);
            list.add(ds.getTitle());
        }

        list.add("+ 添加新身份");

        final String[] items =  (String[])list.toArray(new String[0]);

        AlertDialog.Builder singleChoiceDialog =
                new AlertDialog.Builder(DemandNewActivity.this);
        singleChoiceDialog.setTitle("选择合作身份");
        // 第二个参数是默认选项，此处设置为0
        singleChoiceDialog.setSingleChoiceItems(items, 0,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        yourChoice = which;
                    }
                });
        singleChoiceDialog.setPositiveButton("确 定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (yourChoice != -1) {
                            if (yourChoice == items.length -1 ) {
                                Intent intent = new Intent();
                                intent.putExtra( "id", 0);

                                intent.setClass( DemandNewActivity.this, ConfirmOrgActivity.class);
                                startActivityForResult(intent ,MEMBER_CODE);
                            }


                            if (yourChoice < items.length -1 ) {
                                demand.setMember_title(members.get(yourChoice).getTitle());
                                demand.setMember_id(members.get(yourChoice).getId());
                                memberTitle.setText(demand.getMember_title());
                                memberTitle.setTextColor(ContextCompat.getColor(DemandNewActivity.this,R.color.colorPrimaryDark));
                                if (!is_new) {
                                    Common.setDemandAttr(demand.getId(), "member_id", demand.getMember_id() + "");
                                }
                            }
                            changed = true;
                        }
                    }
                });

        singleChoiceDialog.show();

    }

    private void renderRefer_feeInput() {
        Intent intent = new Intent();
        intent.putExtra("type","refer_fee");
        intent.putExtra( "content", demand.getRefer_fee() +"" );

        intent.putExtra("help", "请填写悬赏介绍的金额" );

        intent.setClass(DemandNewActivity.this,  InputActivity.class);
        startActivityForResult(intent,REFER_FEE_CODE);
    }

    private void completeTitle() {
        Intent intent = new Intent();
        intent.putExtra("type","demandtitle");
        if ( demand.getTitle().length() > 50){
            intent.putExtra("content", demand.getTitle().substring(0,50));
        }else {
            intent.putExtra("content", demand.getTitle());
        }
        
        intent.putExtra("help", "请填写标题" );
        
        intent.setClass(DemandNewActivity.this,  InputActivity.class);
        startActivityForResult(intent,TITLE_CODE);
    }

    private void renderResourceInput(){
        Intent intent = new Intent();
        intent.putExtra("type","demandresource");
        intent.putExtra( "content", demand.getResourcex() );

        intent.putExtra("help", getString(R.string.demand_resources) );
        
        intent.setClass(DemandNewActivity.this,  InputActivity.class);
        startActivityForResult(intent,RESOURCE_CODE);

    }

    private void loadTransactionList(){
        AsyncTask<Void, Void, GetTransactionListResponse> task =new AsyncTask<Void, Void, GetTransactionListResponse>() {
            @Override
            protected GetTransactionListResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<GetTransactionListResponse> responseCall = svc.getTransactionList(userId);
                try {
                    GetTransactionListResponse response = responseCall.execute().body();
                    return response;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
            @Override
            protected void onPostExecute(final GetTransactionListResponse response) {
                if (response != null && response.getContent() !=null) {
                    transactionlist = response.getContent();
                    if (is_new) {
                        for (TransactionOption io : transactionlist) {
                            if (io.getSelected()) {
                                demand.setTransaction( io.getNo());
                                transactionTxt.setText( io.getName() + "");
                                if (io.getNo() == -1){
                                    transactionTxt.setTextColor(ContextCompat.getColor(DemandNewActivity.this,R.color.colorSubTitleText));
                                }else{
                                    transactionTxt.setTextColor(ContextCompat.getColor(DemandNewActivity.this,R.color.colorPrimaryDark));
                                }
                            }
                        }
                    }

                    if (!response.getCondition().equals("")){
                        transactionExplan.setText(response.getCondition());
                    }

                }

            }
            @Override
            protected void onCancelled() {
            }
        };
        task.execute((Void)null);
    }


    private void loadMembers(){

        AsyncTask<Void, Void, GetMyMemberResponse> task =new AsyncTask<Void, Void, GetMyMemberResponse>() {
            @Override
            protected GetMyMemberResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<GetMyMemberResponse> responseCall = svc.getMyMember(userId,"","");
                try {
                    GetMyMemberResponse response = responseCall.execute().body();
                    return response;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
            @Override
            protected void onPostExecute(final GetMyMemberResponse response) {
                if (response != null && response.getContent() !=null){
                    members = response.getContent();

                    SharedPreferences shared = getSharedPreferences("login", MODE_PRIVATE);

                    String person_business = shared.getString("business_name", "")  ;
                    MemberSummary ms = new MemberSummary();
                    ms.setId(0);
                    if (person_business.equals("")){
                        ms.setTitle("业务负责人");
                    }else {
                        ms.setTitle("[" + person_business + "]业务负责人");
                    }
                    members.add(0,ms);
//                    if (demand.getMember_id() == 0 && members.size()>0 ){
//                        for ( MemberSummary ms : members) {
//                            if (ms.getCurrent()) {
//                                demand.setMember_id(ms.getId());
//                                demand.setMember_title(ms.getTitle());
//                                memberTitle.setText(demand.getMember_title());
//                                memberTitle.setTextColor(ContextCompat.getColor(DemandNewActivity.this,R.color.colorPrimaryDark));
////                                if (!is_new) {
////                                    Common.setDemandAttr(demand.getId(), "member_id", demand.getMember_id() + "");
////                                }
//                                changed = true;
//                            }
//                        }
//                    }
                }

            }
            @Override
            protected void onCancelled() {
            }
        };
        task.execute((Void)null);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent intent = new Intent();
        intent.putExtra("changed", changed );
        intent.putExtra( "demand_id", demand.getId() );
        intent.putExtra( "demand_title", demand.getTitle() );
        setResult(0, intent);
        finish();
        return true;
    }


    private void uploadVideo(  String  videoPathOrigin ,final String filename ){
        progress.setVisibility(View.VISIBLE);
        progress.setProgress( 10  );
//        String cachepath = Common.getDiskCachePath(this);

//        Common.cutMp4(1, 60*1000, videoPathOrigin, cachepath, filename);

//        final String videoPath  = cachepath + "/" + filename;
        final String videoPath  =   videoPathOrigin;
        TimerTask task = new TimerTask(){
            public void run(){
                progress.setProgress( 40  );
                final File file = new File(videoPath);
                if (file.length() < 1000) {
                    DemandNewActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            progress.setVisibility(View.INVISIBLE);
                            Common.alert(DemandNewActivity.this, "上传失败");
                        }
                    });
                    return;
                }

                OSS oss = FileUtil.getOss(getApplicationContext());
                PutObjectRequest put = new PutObjectRequest(FileUtil.videoBucketName, filename, videoPath);

// 异步上传时可以设置进度回调
                put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
                    @Override
                    public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                        progress.setProgress(  Math.round( 100* currentSize / totalSize)  );
                    }
                });

                OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                    @Override
                    public void onSuccess(PutObjectRequest request, PutObjectResult result) {
//                Toast.makeText(DemandNewActivity.this,"上传成功",Toast.LENGTH_SHORT).show();
//                        Common.setDemandAttr(demand.getId(),"image","aliyun"+filename,"add");
                        final String videoUrl = "https://woyaooovideo.oss-cn-hangzhou.aliyuncs.com/" + filename;


                        DemandNewActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                progress.setProgress(  100  );
                                progress.setVisibility(View.INVISIBLE);
                                mediaAdapter.addMedia(  videoUrl ,"aliyun"+filename);
                            }
                        });


                    }

                    @Override
                    public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                        // 请求异常
                        if (clientExcepion != null) {
                            // 本地异常如网络异常等
                            clientExcepion.printStackTrace();
                        }
                        if (serviceException != null) {
                            // 服务异常

                        }

                        DemandNewActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Common.alert(DemandNewActivity.this,"上传失败");
                            }
                        });

                    }
                });

            }
        };
        Timer timer = new Timer();
        timer.schedule(task, 1000*3);
        progress.setProgress( 20  );



    }

    private void uploadImage( final String picturePath, final String filename ){
        progress.setVisibility(View.VISIBLE);
        OSS oss = FileUtil.getOss(getApplicationContext());
        PutObjectRequest put = new PutObjectRequest(FileUtil.bucketName, filename, picturePath);


// 异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                progress.setProgress(  Math.round( 100* currentSize / totalSize)  );
            }
        });

        OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                final String picUrl = "https://woyaooo1.oss-cn-hangzhou.aliyuncs.com/" + filename;
                DemandNewActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        progress.setProgress(  100  );
                        progress.setVisibility(View.INVISIBLE);
                        mediaAdapter.addMedia(  picUrl ,"aliyun"+filename);

                    }
                });

            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常

                }
                progress.setVisibility(View.INVISIBLE);
                Toast.makeText(DemandNewActivity.this,"上传失败",Toast.LENGTH_SHORT).show();
            }
        });

    }


    private void SuceedFinish(){
        setUserDemand_id( demand.getId());
                Intent intent = new Intent();
                intent.putExtra("changed", changed);
                intent.putExtra("demand_id", demand.getId());
        intent.putExtra("demand_title", demand.getTitle());
                setResult(666, intent);
                finish();
    }


    private void addDemand(  ) {

//        final String pics = Common.getMediaIds( mediaAdapter.getMedias());


        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
//        progressDialog.setMessage("拼命加载中······");
        progressDialog.show();

        AsyncTask<Void, Void, BaseResponse> task = new AsyncTask<Void, Void, BaseResponse>() {
            @Override
            protected BaseResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);

                Call<BaseResponse> responseCall = svc.addDemand(  userId,   demand.getMember_id() ,Common.KeyValueToNos(demand.getHow_list()),Common.KeyValueToNos(demand.getType_list()),Common.KeyValueToNos(demand.getTypes_list()),demand.getTitle() ,demand.getResourcex(),demand.getMain_image(), Common.getMediaIds(demand.getMedias()) , demand.getRequirement(), Common.KeyValueToNos(demand.getInclude()) , Common.KeyValueToNos(demand.getRelation())  ,demand.getAccess_right(),"0", demand.getCommentable(),demand.getRefer_fee(),demand.getEnduse(),demand.getSpecification(),demand.getProcessing(),demand.getValue(),demand.getQuantity(),demand.getTransaction());
                BaseResponse response = null;
                try {
                    response = responseCall.execute().body();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return response;
            }

            @Override
            protected void onPostExecute(final BaseResponse response) {
                if (response != null ){

                    if ( response.isSuccess()) {
                        demand.setId(Integer.parseInt( response.getMessage()));
                        setUserDemand_id( demand.getId());
                        is_new = false;
                        changed = true;
                        Dialog alertDialog = new AlertDialog.Builder(DemandNewActivity.this).
                                setTitle("信息").
                                setMessage("已经发布，请抓住合作机会，一起成就事业！").
                                setIcon(R.drawable.ic_launcher).
                                setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                        SuceedFinish();
                                    }
                                }).
                                create();
                        alertDialog.show();
                    }
                    else{
                        alertHandle( response);

                    }
                } else {
                    Common.alert( DemandNewActivity.this, "系统发生错误");
                }
                progressDialog.dismiss();
            }
            @Override
            protected void onCancelled() {
                progressDialog.dismiss();
            }
        };
        task.execute((Void) null);
    }
    private void renderMoney( ){
        Intent intent = new Intent();
        intent.putExtra("money", 100.0);
        intent.setClass(DemandNewActivity.this, MoneyActivity.class);
        startActivity(intent);
    }

    public void renderVerify(){
        Intent intent = new Intent();
        intent.setClass(DemandNewActivity.this, VerifyActivity.class);
        startActivity(intent);
    }
    public  void CompleteAccount(){

        Intent intent = new Intent();
        intent.putExtra("from", "demand"  );
        intent.setClass(DemandNewActivity.this, AccountActivity.class);
        startActivity(intent);
    }

    private void alertHandle(final BaseResponse response){

        Dialog alertDialog = new AlertDialog.Builder(this).
                setTitle("信息").
                setMessage(response.getMessage()).
                setIcon(R.drawable.ic_launcher).
                setPositiveButton("确定", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        if (response.getCondition().equals("charge") ){
                            renderMoney();
                        }

                        if (response.getCondition().equals("personal") ){
                            CompleteAccount();
                        }

                        if (response.getCondition().equals("verify") ){
                            renderVerify();
                        }
                    }
                }).
                create();
        alertDialog.show();
    }


    private void loadDemand( ) {
        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("正在获取数据······");
        progressDialog.show();

        AsyncTask<Void, Void, GetDemandResponse> task = new AsyncTask<Void, Void, GetDemandResponse>() {
            @Override
            protected GetDemandResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);

                Call<GetDemandResponse> responseCall = svc.getDemand(userId,demand.getId());
                GetDemandResponse response = null;
                try {
                    response = responseCall.execute().body();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return response;
            }

            @Override
            protected void onPostExecute(final GetDemandResponse response) {
                if (response != null && response.getContent() != null) {
                    renderDemand( response) ;
                }
                progressDialog.dismiss();
            }
            @Override
            protected void onCancelled() {
                progressDialog.dismiss();
            }
        };
        task.execute((Void) null);
    }

    private void renderDemand(GetDemandResponse response) {

        progressDialog.dismiss();
        loading = true;

        demand = response.getContent();

        if ( demand.getAccess_right().equals("public")){
            demandClose.setText( "关闭");
        }else{
            demandClose.setText( "激活");
        }
        this.setTitle(demand.getDisplayTitle());

      
        if (!demand.getTitle().equals("")){
            titleTxt.setText( demand.getTitle());
            titleTxt.setTextColor(ContextCompat.getColor(DemandNewActivity.this,R.color.colorPrimaryDark));
        }

        if (!demand.getResourcex().equals("")) {
            resourceTxt.setText(demand.getResourcex());
            resourceTxt.setTextColor(ContextCompat.getColor(DemandNewActivity.this,R.color.colorPrimaryDark));
        }


        mediaAdapter = new MediaAdapter(this, demand.getMedias());
        mediaAdapter.setChangedHandler(new MediaAdapter.Changed() {
            @Override
            public void Changed(Integer count) {

                
                if (!is_new){
                    Common.setDemandAttr(demand.getId(),"image",Common.getMediaIds(mediaAdapter.getMedias()));
                }
            }
        });
        recyclerView.setAdapter(mediaAdapter);



        if ( demand.getHow_list().size()> 0) {
            howTxt.setText(Common.KeyValueToNames(demand.getHow_list()));
            howTxt.setTextColor(ContextCompat.getColor(DemandNewActivity.this,R.color.colorPrimaryDark));
        }

        if ( demand.getType_list().size()> 0) {
            typeTxt.setText(Common.KeyValueToNames(demand.getType_list()));
            typeTxt.setTextColor(ContextCompat.getColor(DemandNewActivity.this,R.color.colorPrimaryDark));
        }

        if ( demand.getTypes_list().size()> 0) {
            typesText.setText(Common.KeyValueToNames(demand.getTypes_list()));
            typesText.setTextColor(ContextCompat.getColor(DemandNewActivity.this,R.color.colorPrimaryDark));
        }
        
        memberTitle.setText(demand.getMember_title());

        if ( demand.getRefer_fee() > 0 ) {
            referFeeTxt.setTextColor(ContextCompat.getColor(DemandNewActivity.this,R.color.colorPrimaryDark));
        }
        referFeeTxt.setText( demand.getRefer_fee() +"");

        if ( demand.getTransaction() >= 0 ) {
            transactionTxt.setTextColor(ContextCompat.getColor(DemandNewActivity.this,R.color.colorPrimaryDark));
        }
        transactionTxt.setText(demand.getTransaction_text() );
        

        loading = false;
    }

    public   void setDemandAccessRight( final String access_right ) {
        AsyncTask<Void, Void, BaseResponse> task = new AsyncTask<Void, Void, BaseResponse>() {
            @Override
            protected BaseResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<BaseResponse> responseCall = svc.setDemandAttr(WoyaoooApplication.userId,demand.getId(),"access_right",access_right,"");
                BaseResponse ret = null ;
                try {
                    ret = responseCall.execute().body();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return ret;
            }

            @Override
            protected void onPostExecute(final BaseResponse response) {
                if (response != null) {
                    if (response.isSuccess()){
                        if (access_right.equals("public")) {
                            demand.setAccess_right("public");
                            demandClose.setText("关闭");
                            Common.showSnack(DemandNewActivity.this, demandClose, "已经激活！");
                        }else{
                            demand.setAccess_right("private");
                            demandClose.setText("激活");
                            Common.showSnack(DemandNewActivity.this, demandClose, "已经关闭！");
                        }

                    }
                } else {
                    Common.alert( DemandNewActivity.this,"系统发生错误");
                }
            }

            @Override
            protected void onCancelled() {
            }
        };
        task.execute((Void) null);
    }

    public   void deleteDemand(  ) {
        AsyncTask<Void, Void, BaseResponse> task = new AsyncTask<Void, Void, BaseResponse>() {
            @Override
            protected BaseResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<BaseResponse> responseCall = svc.deleteDemand(WoyaoooApplication.userId,demand.getId());
                BaseResponse ret = null ;
                try {
                    ret = responseCall.execute().body();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return ret;
            }

            @Override
            protected void onPostExecute(final BaseResponse response) {
                if (response != null) {
                    if (response.isSuccess()){
                            Common.showSnack(DemandNewActivity.this, demandClose, response.getMessage());
                        SuceedFinish();
                    }else{
                        Common.showSnack(DemandNewActivity.this, demandClose, response.getMessage());
                    }
                } else {
                    Common.alert( DemandNewActivity.this,"系统发生错误");
                }
            }

            @Override
            protected void onCancelled() {
            }
        };
        task.execute((Void) null);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);



        if(requestCode == TITLE_CODE  && resultCode == 666 ) {
            CharSequence con = data.getCharSequenceExtra("content");
            if (con == null) return;
            demand.setTitle(con.toString());
            titleTxt.setText( con);
            titleTxt.setTextColor(ContextCompat.getColor(DemandNewActivity.this,R.color.colorPrimaryDark));
            changed = true;
            if (!is_new ) Common.setDemandAttr(demand.getId(), "title", con.toString());
        }else if(requestCode == MEMBER_CODE  && resultCode == 666 ) {
            Integer mem_id = data.getIntExtra("member_id",0);
            demand.setMember_id( mem_id);
            demand.setMember_title(data.getStringExtra("member_title"));
            memberTitle.setTextColor(ContextCompat.getColor(DemandNewActivity.this,R.color.colorPrimaryDark));
            memberTitle.setText( demand.getMember_title());
            Boolean changed = data.getBooleanExtra("changed", true);
            if (changed) {
                loadMembers();
            }
            if (!is_new) {
                Common.setDemandAttr(  demand.getId() ,"member_id",demand.getMember_id() +"" );
            }
        }else if(requestCode == RESOURCE_CODE  && resultCode == 666 ) {
            CharSequence con = data.getCharSequenceExtra("content");
            if (con == null) return;
            demand.setResourcex(con.toString());
            resourceTxt.setText( con);
            resourceTxt.setTextColor(ContextCompat.getColor(DemandNewActivity.this,R.color.colorPrimaryDark));
            changed = true;
            if (!is_new ) Common.setDemandAttr(demand.getId(), "resourcex", con.toString());


        }
        else if(requestCode == REFER_FEE_CODE  && resultCode == 666 ) {
            String con = data.getStringExtra("content");
            if (con == null) return;
            demand.setRefer_fee(  Float.parseFloat( con ) );
            referFeeTxt.setText( demand.getRefer_fee().toString());
            referFeeTxt.setTextColor(ContextCompat.getColor(DemandNewActivity.this,R.color.colorPrimaryDark));
            changed = true;
            if (!is_new ) Common.setDemandAttr(demand.getId(), "refer_fee", demand.getRefer_fee().toString());


        }else if(requestCode == TYPES_CODE && resultCode ==666) {
            KeyValueList thelist = (KeyValueList) data.getExtras().get("result");
            demand.setTypes_list(thelist.getContent());

            if (thelist.getContent().size() > 0 ) {
                typesText.setText(Common.KeyValueToNames(demand.getTypes_list()));
                typesText.setTextColor(ContextCompat.getColor(DemandNewActivity.this, R.color.colorPrimaryDark));
            }else{
                typesText.setText(getString(R.string.demand_types));
                typesText.setTextColor(ContextCompat.getColor(DemandNewActivity.this, R.color.colorLight));
            }

            if (!is_new ) Common.setDemandAttr(demand.getId(), "types", Common.KeyValueToNos(demand.getTypes_list()));

            changed = true;
        }else if(requestCode == TYPE_CODE && resultCode ==666) {
            KeyValueList thelist = (KeyValueList) data.getExtras().get("result");
            demand.setType_list(thelist.getContent());

            if (thelist.getContent().size() > 0 ) {
                typeTxt.setText(Common.KeyValueToNames(demand.getType_list()));
                typeTxt.setTextColor(ContextCompat.getColor(DemandNewActivity.this, R.color.colorPrimaryDark));
            }else{
                typeTxt.setText(getString(R.string.demand_type));
                typeTxt.setTextColor(ContextCompat.getColor(DemandNewActivity.this, R.color.colorLight));
            }

            if (!is_new ) Common.setDemandAttr(demand.getId(), "type", Common.KeyValueToNos(demand.getType_list()));

            changed = true;
        }else if(requestCode == HOW_CODE && resultCode ==666) {
            KeyValueList thelist = (KeyValueList) data.getExtras().get("result");
            demand.setHow_list(thelist.getContent());

            if (thelist.getContent().size() > 0 ) {
                howTxt.setText(Common.KeyValueToNames(demand.getHow_list()));
                howTxt.setTextColor(ContextCompat.getColor(DemandNewActivity.this, R.color.colorPrimaryDark));
            }else{
                howTxt.setText("请选择");
                howTxt.setTextColor(ContextCompat.getColor(DemandNewActivity.this, R.color.colorLight));
            }

            if (!is_new ) Common.setDemandAttr(demand.getId(), "how", Common.KeyValueToNos(demand.getHow_list()));

            changed = true;
        }else if(requestCode == CHOOSE_MEDIA_CODE){
            try{
                Uri selectedImage = data.getData();
                String localpicpath = Common.getPath(DemandNewActivity.this,selectedImage);
                if (localpicpath.endsWith("mp4")){
                    uploadVideo(  localpicpath, FileUtil.getVideoObjectKey());
                }else {
                    uploadImage(localpicpath, FileUtil.getPicObjectKey());
                }
            }catch(Exception e) {
                e.printStackTrace();
            }
            
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent();
            intent.putExtra("changed", changed );
            intent.putExtra( "demand_id", demand.getId() );
            intent.putExtra( "demand_title", demand.getTitle() );
            setResult(0, intent);
            finish();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }


}
